﻿using System;
using System.Diagnostics;
using System.IO;
using System.Windows;
using Microsoft.WindowsAPICodePack.Dialogs;

namespace ForguncySecurityProviderCreator;

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public SpCreatorViewModel ViewModel => DataContext as SpCreatorViewModel;

    public MainWindow()
    {
        InitializeComponent();
        DataContext = new SpCreatorViewModel();
    }

    private void SelectInstallationFolder_Click(object sender, RoutedEventArgs e)
    {
        var cofDialog = new CommonOpenFileDialog();
        cofDialog.IsFolderPicker = true;
        cofDialog.InitialDirectory = ViewModel.ForguncyInstallationPath;

        if (cofDialog.ShowDialog() == CommonFileDialogResult.Ok)
        {
            ViewModel.ForguncyInstallationPath = cofDialog.FileName;
        }
    }

    private void SelectSaveFolder_Click(object sender, RoutedEventArgs e)
    {
        var cofDialog = new CommonOpenFileDialog();
        cofDialog.IsFolderPicker = true;
        cofDialog.InitialDirectory = ViewModel.SpSaveFolderPath;

        if (cofDialog.ShowDialog() == CommonFileDialogResult.Ok)
        {
            ViewModel.SpSaveFolderPath = cofDialog.FileName;
        }
    }

    private async void OK_Click(object sender, RoutedEventArgs e)
    {
        if (!TryValidAndResolveParam(out var forguncyExePath, out var forguncyWebsitePath))
        {
            return;
        }

        var fileInfo = FileVersionInfo.GetVersionInfo(forguncyExePath);
        ViewModel.ForguncyVersion = Version.Parse(fileInfo.FileVersion!);
        ViewModel.ForguncyWebsitePath = forguncyWebsitePath;

        try
        {
            await SpCreator.CreateSpByTemplateAsync(ViewModel);
            MessageBox.Show("创建成功", "成功", MessageBoxButton.OK);
        }
        catch (Exception exception)
        {
            ShowError("创建失败：" + exception.Message, exception);
        }
    }

    private bool TryValidAndResolveParam(out string forguncyExePath, out string forguncyWebsitePath)
    {
        forguncyExePath = null;
        forguncyWebsitePath = null;
        if (string.IsNullOrWhiteSpace(ViewModel.Name))
        {
            ShowError("安全提供程序的名称不能为空");
            return false;
        }

        if (string.IsNullOrWhiteSpace(ViewModel.ForguncyInstallationPath))
        {
            ShowError("活字格设计器安装路径不能为空");
            return false;
        }

        if (string.IsNullOrWhiteSpace(ViewModel.SpSaveFolderPath))
        {
            ShowError("安全提供程序保存路径不能为空");
            return false;
        }

        forguncyExePath = Path.Combine(ViewModel.ForguncyInstallationPath, "Forguncy.Server2", "designerBin",
            "Forguncy.exe");
        forguncyWebsitePath = Path.Combine(ViewModel.ForguncyInstallationPath, "Forguncy.Server2");
        if (!File.Exists(forguncyExePath))
        {
            forguncyExePath =
                Path.Combine(ViewModel.ForguncyInstallationPath, "Website", "designerBin", "Forguncy.exe");
            forguncyWebsitePath = Path.Combine(ViewModel.ForguncyInstallationPath, "Website");
            if (!File.Exists(forguncyExePath))
            {
                ShowError("找不到文件：" + forguncyExePath);
                return false;
            }
        }

        ViewModel.SpProjectPath = Path.Combine(ViewModel.SpSaveFolderPath, ViewModel.Name);
        if (Directory.Exists(ViewModel.SpProjectPath))
        {
            ShowError("文件夹：" + ViewModel.SpProjectPath + "已存在，请选择其他位置");
            return false;
        }

        return true;
    }

    private void ShowError(string message, Exception e = null)
    {
        MessageBox.Show(message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
        if (e != null)
        {
            throw e;
        }
    }

    private void Cancel_Click(object sender, RoutedEventArgs e)
    {
        Close();
    }
}